package com.lrogzin.memo.Util;

import androidx.annotation.NonNull;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.lrogzin.memo.Bean.NoteBean;

import java.util.ArrayList;
import java.util.List;

public class FirebaseHelper {
    private DatabaseReference notesRef;
    private OnNotesLoadedListener listener;

    public FirebaseHelper(String userId) {
        notesRef = FirebaseDatabase.getInstance().getReference("users/" + userId + "/notes");
    }

    public interface OnNotesLoadedListener {
        void onNotesLoaded(List<NoteBean> notes);
        void onError(DatabaseError error);
    }

    public void setOnNotesLoadedListener(OnNotesLoadedListener listener) {
        this.listener = listener;
    }

    // 从云端加载笔记数据
    public void loadNotesFromCloud() {
        notesRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                List<NoteBean> notes = new ArrayList<>();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    NoteBean note = snapshot.getValue(NoteBean.class);
                    notes.add(note);
                }
                if (listener != null) {
                    listener.onNotesLoaded(notes);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                if (listener != null) {
                    listener.onError(databaseError);
                }
            }
        });
    }

    // 保存笔记到云端
    public void saveNoteToCloud(NoteBean note) {
        String noteId = note.getNoteId();
        if (noteId == null || noteId.isEmpty()) {
            noteId = notesRef.push().getKey(); // 生成唯一ID
            note.setNoteId(noteId); // 为笔记设置ID
        }
        notesRef.child(noteId).setValue(note);
    }

    // 删除云端笔记
    public void deleteNoteFromCloud(String noteId) {
        notesRef.child(noteId).removeValue();
    }
} 